#include "ServerIoThread.h"

using namespace simodo::edit::plugin::model_server;

// Один на чтение, другой на запись
constexpr int N_POOL_THREADS = 2;

ServerIoThread::ServerIoThread(std::string process_path, std::vector<std::string> process_args)
    : _pool(N_POOL_THREADS)
    , _service(_io, process_path, process_args)
{}

ServerIoThread::~ServerIoThread()
{
    stop();
}

void ServerIoThread::start()
{
    if (isRunning())
    {
        return;
    }

    _io_work = std::make_shared<boost::asio::io_service::work>(_io);
    for (int i = 0; i < N_POOL_THREADS; ++i)
    {
        boost::asio::post(_pool, [this] { _io.run(); });
    }
}

bool ServerIoThread::isRunning()
{
    return _io_work != nullptr;
}

void ServerIoThread::stop()
{
    _io_work = nullptr;
    _service.stop();
}
